package com.bjpowernode.filter;

import com.bjpowernode.beans.User;
import com.bjpowernode.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

//过滤器拦截静态页面
public class MyLoginFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        //
        int jsSum = req.getRequestURI().lastIndexOf(".js");
        int cssSum = req.getRequestURI().lastIndexOf(".css");
        if(jsSum!=-1){
            chain.doFilter(req, res);
            return;
        }
        if(cssSum!=-1){
            chain.doFilter(req, res);
            return;
        }

        System.out.println("过滤器：拦截页面" + req.getRequestURI());
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");

        if (user == null) {
            //获取cookies里面的用户账号和密码，并且再次进入数据库验证，如果验证成功，也可以进去（免登录）
            String loginAct = "";
            String loginPwd = "";
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("loginAct")) {
                    System.out.println("过滤器：找到了loginAct的cookies其值为：" + cookie.getValue());
                    loginAct = cookie.getValue();
                }
                if (cookie.getName().equals("loginPwd")) {
                    System.out.println("过滤器：找到了loginPwd的cookies其值为：" + cookie.getValue());
                    loginPwd = cookie.getValue();
                }
            }

            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            UserServices userServices = context.getBean(UserServices.class);
            User userTemp = userServices.login(loginAct, loginPwd);
            if (userTemp == null) {
                System.out.println("过滤器：没有用户" + req.getRequestURI());
                res.sendRedirect("/static/login.html");
            } else {
                //需要添加HttpSession
                session.setAttribute("user", userTemp);
                chain.doFilter(req, res);
            }
        }
        else {
            //放行
            chain.doFilter(req, res);
        }
    }
}
